package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"vipshop-app/models/cache"
	"vipshop-app/models/mysql"
	"vipshop-app/pkg"
	"vipshop-app/vipshopapc/internal/svc"
	"vipshop-app/vipshopapc/vipshopapc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *vipshopapc.UpdatePasswordRequest) (*vipshopapc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	getSms := cache.Rdb.Get(l.ctx, "sendSms"+"update"+in.Mobile)
	if getSms.Val() != in.CaptSms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在，请先注册")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("旧密码输入错误,请重新输入")
	}

	if in.Password == in.PasswordNew {
		return nil, fmt.Errorf("旧密码与新密码一致,请重新输入新密码")
	}

	user = mysql.User{
		Model: gorm.Model{
			ID: user.ID,
		},
		Password: pkg.Md5(in.PasswordNew),
	}
	err := mysql.DB.Debug().Where("id = ?", user.ID).Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("")
	}

	//成功后删除短信缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"update"+in.Mobile)
	return &vipshopapc.UpdatePasswordResponse{Id: int64(user.ID)}, nil
}
